package com.example.home.view

import android.os.Bundle
import android.renderscript.ScriptGroup.Binding
import android.view.View
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.example.base.RoutePath
import com.example.common.event.LiveDataBus
import com.example.common.event.LiveDataBusEvent
import com.example.common.mvi.BaseMviFragment
import com.example.home.R
import com.example.home.adapter.HomeVideoListAdapter
import com.example.home.databinding.FragmentHomeListBinding
import com.example.login.intent.SimpleViewIntent
import com.example.login.state.SimpleUiState
import com.example.login.vm.SimpleViewModel
import com.example.main.ui.home.entity.SimpleVideoEntity
import kotlinx.coroutines.launch


class HomeListFragment : BaseMviFragment<FragmentHomeListBinding>() {
    private val mViewModel:SimpleViewModel by activityViewModels()
    private var typeId:Int = -1
    private var channelId:String = ""
    private var pageIndex = 1
    private var pageSize = 10
    private var simpleVideoList = mutableListOf<SimpleVideoEntity>()
    private lateinit var mRecyclerView: RecyclerView
    private lateinit var mAdapter: HomeVideoListAdapter
    companion object{
        @JvmStatic
        fun newInstance(tabId:Int,channelId:String) =
            HomeListFragment().apply {
                arguments = Bundle().apply {
                    putInt("tabId",tabId)
                    putString("channelId",channelId)
                }
            }
    }


    override fun initViews() {
        arguments?.let {
            typeId=it.getInt("tabId")
            channelId=it.getString("channelId").toString()
        }
        binding.refreshLayout.setOnRefreshListener{
            pageIndex=1
            refreshOrMoreList()
        }
        mRecyclerView = binding.rvHomeList
        mAdapter = HomeVideoListAdapter(simpleVideoList)
        mAdapter.apply {
            preloadEndCount=4
            preloadData={
                pageIndex+=1
                refreshOrMoreList()
            }
        }
        mAdapter.setOnItemClickListener(object :HomeVideoListAdapter.OnItemClickListener{
            override fun onItemClick(v: View, position: Int) {
                when(v.id){
                    R.id.main_image->{
                        ARouter.getInstance().build(RoutePath.ROUTE_DETAIL).withInt("typeId",typeId).withString("channelId" ,channelId).withSerializable("videoEntity",simpleVideoList[position]).navigation()
                    }
                    R.id.iv_comment->{
                        LiveDataBus.with<LiveDataBusEvent>("video_options").value=
                            LiveDataBusEvent(100,simpleVideoList[position])
                    }
                    R.id.iv_more->{
                        LiveDataBus.with<LiveDataBusEvent>("video_options").value=
                            LiveDataBusEvent(101,simpleVideoList[position])
                    }
                }
            }

        })
        mRecyclerView.layoutManager = LinearLayoutManager(requireContext(),LinearLayoutManager.VERTICAL,false)
mRecyclerView.swapAdapter(mAdapter,true)



    }

    private fun refreshOrMoreList() {
        lifecycleScope.launch {
            if(typeId==-1){
                mViewModel.channel.send(SimpleViewIntent.RecommendToServer(pageIndex,pageSize))
            }else{
                mViewModel.channel.send(SimpleViewIntent.VideoToServer(channelId,pageIndex,pageSize))
            }
        }
    }

    override fun onResume() {
        super.onResume()
        lazyLoadData()
    }

    override suspend fun collectUiState() {
        mViewModel.uiState.collect{
            when(it){
                is SimpleUiState.VideoSuccess->setPageData(it.data)
                is SimpleUiState.VideoFailure->{
                    if(pageIndex>1){
                        pageIndex=-1
                    }
                    if(simpleVideoList.size>0){
                        simpleVideoList.clear()
                        mAdapter.notifyDataSetChanged()
                    }
                    showToastMessage(it.msg)
                }
                else->{}
            }
        }
    }

    private fun setPageData(list: List<SimpleVideoEntity>) {
//        if(pageIndex==1){
//            binding.refreshLayout.finishRefresh()
//            simpleVideoList.clear()
//        }
        simpleVideoList.addAll(list)
        mAdapter.notifyDataSetChanged()
    }

    private fun lazyLoadData() {
        lifecycleScope.launch {
            if(typeId==-1){
                mViewModel.channel.send(SimpleViewIntent.RecommendToServer(pageIndex,pageSize))
            }else{
                mViewModel.channel.send(SimpleViewIntent.VideoToServer(channelId,pageIndex,pageSize))
            }
        }
    }

    override fun getLayoutId(): Int = R.layout.fragment_home_list

}